<?php
declare(strict_types=1);

namespace app\model;


use think\Model;
use app\exceptions\SystemException;
use think\facade\Db;

class Uid extends Model
{
    protected $table = 'test_uid_and_clientid';


    /**
     * @param array $data
     * @return bool
     * @throws SystemException
     * @throws \think\exception\PDOException
     */
    public function bindUidAndClientId(array $data)
    {

        Db::startTrans();
        try {
            //删除旧的 客户端id记录
            $this->where(['client_id'=> $data['client_id']])->delete();

            if (!$this->isExistByUid($data['uid'])) {
                $this->insert([
                    'uid' => $data['uid'],
                    'client_id' => $data['client_id'],
                    'create_time' => time(),
                    'update_time' => time(),
                ]);
            } else {
                $this->where(['uid' => $data['uid']])->update(
                    ['client_id' => $data['client_id'], 'update_time' => time()]
                );
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            throw new SystemException($e->getMessage());
        }

        return true;
    }

    /**
     * 检查是否存在uid
     * @param $uid
     * @return bool
     * @throws \think\Exception
     */
    public function isExistByUid($uid)
    {
        return $this->where(['uid' => $uid])->count() != 0;
    }

    /**
     * 查询client_id
     * @param $uid
     * @return mixed
     */
    public function getClientIdByUid($uid)
    {
        return $this->where(['uid' => $uid])->value('client_id');
    }
}
